import $utils from '@/utils/fn.js'
import { merge, assign, cloneDeep } from 'lodash-es'
import { serialize } from '@/pages/emr/emrReader.js'
// import Vue from 'vue'
import moment from 'moment'
// @兼容: 治疗方案兼容以前的写法,转化category=>str
export function _parse(category) {
  let str = ''
  let filterRequest = category.allRequest.filter((item) => item.inputs[0].value)
  str = filterRequest.reduce((pre, now) => {
    let rowStr = ''

    // select
    if (now.name !== 'other') {
      let medicine = now.inputs[0]
      let method = now.inputs[1].value
      let eachDose = now.inputs[2].value
      let frequency = now.inputs[3].value

      let medicants = now.medicants
      let targetIdx = -1

      // 值为name
      if (isNaN(Number(medicine.value))) {
        targetIdx = $utils.findIndex(medicants, { drugName: medicine.value })
      } else {
        targetIdx = $utils.findIndex(medicants, { id: medicine.value })
      }

      let target = medicants[targetIdx]

      if (targetIdx != -1) {
        rowStr +=
          [
            target.drugName,
            target.drugSpec || '',
            method || '',
            eachDose || '',
            frequency || '',
          ]
            .filter((item) => item)
            .join(' ') + ';'
      }
    } else {
      // input 其他
      rowStr = now.inputs[0].value
    }

    return (pre += rowStr)
  }, '')

  return str
}

// 诊前收集的病史病例的数据,需要用这个方法整理
// 从诊前收集的小程序代码同步过来的方法
// utils/util.js#flattenArray
// flatten patient history data
export function flattenArray(vmodel, isReview) {
  let copyData = JSON.parse(vmodel)
  // edit value
  function change(key, data) {
    let value = data[key]
    if (!value) return

    let specialExchangeKey = ['seasonChecks', 'causeChecks']
    if (specialExchangeKey.indexOf(key) != -1) {
      // array
      data[key] = value.filter((item) => item.checked).map((item) => item.value)
      if (key === 'seasonChecks' && data[key].length) {
        data.seasonCorrelation = '1'
      }
    } else if (value && Array.isArray(value)) {
      // boolean
      let bool = value
        .filter((item) => item.checked)
        .map((item) => item.value)[0]

      bool = bool === 'true'

      if (key === 'hasFamilyHistory') {
        bool = bool ? '有' : '无'
      }

      // if (['nasitis', 'dermatitis'].includes(key)) {
      //   bool = bool ? 1 : 0;
      // }

      if (
        ['allergyHistory', 'relieverWork', 'nasitis', 'dermatitis'].includes(
          key
        )
      ) {
        bool = bool ? '1' : '0'
      }

      if (['isAsthmaCured'].includes(key)) {
        bool = bool ? 'yes' : 'no'
      }

      // 复诊
      if (
        isReview &&
        ['cough', 'wheezing', 'longTermAdjustment'].includes(key)
      ) {
        bool = bool ? '有' : '无'
      }

      data[key] = bool
    }
  }

  for (let key in copyData) {
    if (key == 'attachments') continue

    for (let subkey in copyData[key]) {
      if ($utils.getTypeOf(copyData[key]) == '[object Object]') {
        change(subkey, copyData[key])
      }
    }
  }

  return copyData
}

// 获取评估控制的文字
export function getEvaluationCtrlText(type, score) {
  let status = ['未得到控制', '部分得到控制', '得到控制']
  if (type == 'TRACK') {
    return score < 80 ? status[0] : status[2]
  } else if (type == 'CACT') {
    return score <= 20 ? status[0] : score < 23 ? status[1] : status[2]
  } else if (type == 'ACT') {
    return score < 20 ? status[0] : score < 25 ? status[1] : status[2]
  }
  return ''
}

// 获取评估控制的颜色class
export function getEvaluationCtrlClass(type, score) {
  if (type == 'TRACK') {
    return score < 80 ? 'danger' : 'success'
  } else if (type == 'CACT') {
    return score <= 20 ? 'danger' : score <= 23 ? 'warning' : 'success'
  } else if (type == 'ACT') {
    return score < 20 ? 'danger' : score < 25 ? 'warning' : 'success'
  }
  return ''
}

// 合并诊前病历到当前的病历(初诊或复诊)
export function mergePrePatientHistoryInfo(vmodel, prePatientInfo) {
  let mergeKey = []
  if (prePatientInfo.patientHistoryJson.type === 'FIRST') {
    // 首诊
    mergeKey = [
      'presentIllnessHistory',
      'pastHistory',
      'familyHistory',
      'diagnosticReport',
      'attachments',
    ]
  } else {
    // 复诊
    mergeKey = ['reviewChiefComplaint', 'diagnosticReport', 'attachments']
  }
  mergeKey.forEach((key) => {
    if (key == 'attachments') {
      vmodel[key] = prePatientInfo.patientHistoryJson[key]
    } else {
      assign(vmodel[key], prePatientInfo.patientHistoryJson[key])
    }
  })
}

// 合并病历
export function mergePreScreening(vmodel, preScreening) {
  let mergeKey = [
    'chiefComplaint',
    'presentIllnessHistory',
    'pastHistory',
    'familyHistory',
    'diagnostic',
    'attachments',
    'personalHistory',
    'diagnosticReport',
    'assExam',
  ]

  // 计算喘息咳嗽的偏移时间
  let creatDate = moment(preScreening.screeningDate)
  let currentDate = moment()
  let offsetDays = currentDate.diff(creatDate, 'd')
  if (offsetDays) {
    let chiefComplaint = preScreening.chiefComplaint

    // 满一个月
    let isFullOneMonths = chiefComplaint.days + offsetDays > 31
    if (isFullOneMonths) {
      chiefComplaint.months = isFullOneMonths
        ? (chiefComplaint.months || 0) + 1
        : chiefComplaint.months
      chiefComplaint.days = (chiefComplaint.days + offsetDays) % 31
    } else {
      chiefComplaint.days = (chiefComplaint.days + offsetDays) % 31
    }
    // 满一年
    if (chiefComplaint.months > 12) {
      chiefComplaint.years = (chiefComplaint.years || 0) + 1
      chiefComplaint.months = chiefComplaint.months % 12
    }
  }
  // 除掉旧诊断 让医生界面通过具体症状进行判断。
  let diagnostic = preScreening.diagnostic
  diagnostic.handChecks = []
  diagnostic.diagnosticType = []

  mergeKey.forEach((key) => {
    if (key == 'attachments') {
      if (preScreening[key])
        assign(vmodel[key], $utils.pureCopy(preScreening[key]))
    } else {
      assign(vmodel[key], $utils.pureCopy(preScreening[key]))
    }
  })
}

// 设置预约页面的默认日期
export function setDefaultDate(vmodel) {
  let months = vmodel.review.months * 30
  let weeks = vmodel.review.weeks * 7
  let days = vmodel.review.days * 1

  let sum = months + weeks + days
  return sum
}

// 获取治疗评估等级
export function getLevelByText(val) {
  if (!val) return ''
  let regLevelText = /(?=第).+?(?=级治疗)/
  let result = val.replace('\n', '').match(regLevelText)
  return (result && result[0].slice(1)) || ''
}

// 控制水平评级class样色
export function getClassInControlLevel(clevel) {
  switch (clevel) {
    // 控制水平
    case 'under_control':
      return 'success'
    case 'well_control':
      return 'success'
    case 'partial_control':
      return 'warning'
    case 'without_control':
      return 'danger'
    // 急性程度
    case 'low':
      return 'success'
    case 'medium':
      return 'success'
    case 'high':
      return 'warning'
    case 'danger':
      return 'danger'
    default:
      return 'info'
  }
}

// 生成首诊病历文字描述
export function genFirstEmrTextContent(fragmentVModel, birthDate) {
  let age = moment().diff(moment(birthDate), 'year')
  let presentIllnessHistoryStr =
    serialize.repeatReason(fragmentVModel) +
    serialize.multiReason(fragmentVModel) +
    serialize.fluquency(fragmentVModel) +
    serialize.season(fragmentVModel) +
    serialize.reveribility(fragmentVModel) +
    serialize.otherPersonality(fragmentVModel)

  let temp = [
    {
      name: '主诉',
      text: [serialize.chiefComplaint(fragmentVModel)],
      imgUrls: [],
      isNameAdded: false,
    },
    {
      name: '现病史',
      text: [presentIllnessHistoryStr],
      imgUrls: [],
      isNameAdded: false,
    },
    {
      name: '既往史',
      text: [serialize.pastHistory(fragmentVModel)],
      imgUrls: [],
      isNameAdded: false,
    },
    {
      name: '个人史',
      text: [serialize.personalHistory(fragmentVModel)],
      imgUrls: [],
      isNameAdded: false,
    },
    {
      name: '家族史',
      text: [serialize.familyHistory(fragmentVModel)],
      imgUrls: [],
      isNameAdded: false,
    },
    {
      name: '体格检查',
      text: [serialize.bodyCheck(fragmentVModel)],
      imgUrls: [],
      isNameAdded: false,
    },
    {
      name: '辅助检查',
      text: [serialize.assExam(fragmentVModel)],
      imgUrls: $utils
        .pureCopy(fragmentVModel.assExam.lungThumbnail || [])
        .concat($utils.pureCopy(fragmentVModel.assExam.allergenImgurl || [])),
      isNameAdded: false,
    },
    {
      name: '诊断',
      text: [serialize.diagnostic(fragmentVModel, age)],
      imgUrls: [],
      isNameAdded: false,
    },
    {
      name: '治疗方案',
      text: [serialize.diagnosticRequest(fragmentVModel)],
      imgUrls: [],
      isNameAdded: false,
    },
    {
      name: '附件',
      text: [''],
      imgUrls: $utils.pureCopy(fragmentVModel.attachments || []),
      isNameAdded: false,
    },
  ]

  return temp
}

export function pastHistoryCompatible(pastHistory, vmodel) {
  pastHistory.nasitis = (pastHistory.nasitis || '0') + ''
  pastHistory.dermatitis = (pastHistory.dermatitis || '0') + ''

  return pastHistory
}
// @兼容: 辅助检查
export function assExamCompatible(assExam, vmodel) {
  let hasProperty = (data, key) => {
    if (typeof data !== 'object') return
    // eslint-disable-next-line no-prototype-builtins
    return data.hasOwnProperty(key)
  }

  if (!hasProperty(assExam, 'allergen')) {
    assExam.allergen = vmodel.pastHistory.allergen || 0
  }

  if (!hasProperty(assExam, 'allergenSources')) {
    assExam.allergenSources = vmodel.pastHistory.allergenSources || []
  }

  if (!hasProperty(assExam, 'milkDiagnosis')) {
    assExam.milkDiagnosis = vmodel.pastHistory.milkDiagnosis || ''
  }

  if (!hasProperty(assExam, 'eggDiagnosis')) {
    assExam.eggDiagnosis = vmodel.pastHistory.eggDiagnosis || ''
  }

  if (!hasProperty(assExam, 'seafoodDiagnosis')) {
    assExam.seafoodDiagnosis = vmodel.pastHistory.seafoodDiagnosis || ''
  }

  if (!hasProperty(assExam, 'dustMitesDiagnosis')) {
    assExam.dustMitesDiagnosis = vmodel.pastHistory.dustMitesDiagnosis || ''
  }

  if (!hasProperty(assExam, 'dustMitesDiagnosis1')) {
    assExam.dustMitesDiagnosis1 = vmodel.pastHistory.dustMitesDiagnosis1 || ''
  }

  if (!hasProperty(assExam, 'dustMitesDiagnosis2')) {
    assExam.dustMitesDiagnosis2 = vmodel.pastHistory.dustMitesDiagnosis2 || ''
  }
  if (!hasProperty(assExam, 'pollenDiagnosis')) {
    assExam.pollenDiagnosis = vmodel.pastHistory.pollenDiagnosis || ''
  }

  if (!hasProperty(assExam, 'allergenImgurl')) {
    assExam.allergenImgurl = vmodel.pastHistory.allergenImgurl || []
  }

  if (!hasProperty(assExam, 'allergenOthers')) {
    assExam.allergenOthers = vmodel.pastHistory.allergenOthers || []
  }

  return assExam
}

// @兼容: 身体检查
export function diagnosticReportCompatible(diagnosticReport) {
  let highPitchedDryStatus = diagnosticReport.highPitchedDryStatus
  if (!Array.isArray(highPitchedDryStatus)) {
    diagnosticReport.highPitchedDryStatus = highPitchedDryStatus
      ? [highPitchedDryStatus]
      : []
  }
  let sonorousRhonchiStatus = diagnosticReport.sonorousRhonchiStatus
  if (!Array.isArray(sonorousRhonchiStatus)) {
    diagnosticReport.sonorousRhonchiStatus = sonorousRhonchiStatus
      ? [sonorousRhonchiStatus]
      : ''
  }

  let raleStatus = diagnosticReport.raleStatus
  if (!Array.isArray(raleStatus)) {
    diagnosticReport.raleStatus = raleStatus ? [raleStatus] : ''
  }

  return diagnosticReport
}

// @兼容:向前兼容治疗方案
// category.allRequest 转化 => longtermTreatmentTpl|emergencyTreatmentTpl
export function diagnosticRequestCompatible(diagnosticRequest) {
  // 改版后的治疗方案
  if (diagnosticRequest.version == '2020-12-02') return diagnosticRequest

  // 长期治疗模板
  if (diagnosticRequest.longtermTreatmentTpl === undefined) {
    let category = diagnosticRequest.category[0]
    diagnosticRequest.longtermTreatmentTpl = _parse(category)
  }

  // 紧急治疗模板
  if (diagnosticRequest.emergencyTreatmentTpl === undefined) {
    let category = diagnosticRequest.category[1]
    diagnosticRequest.emergencyTreatmentTpl = _parse(category)
  }

  // 其他治疗方案
  if (diagnosticRequest.otherTreatmentTpl === undefined) {
    diagnosticRequest.otherTreatmentTpl = ''
  }

  delete diagnosticRequest.category

  return diagnosticRequest
}

// 前版本的治疗方案兼容，
// 如果以前的治疗方案，那么需要放到结构话的治疗方案的remark.content里面
export function setPreviewDiagnosticReqToRemark(vmodel, remark) {
  // 兼容以前的治疗方案
  if (vmodel.diagnosticRequest.version != '2020-12-02') {
    return (
      vmodel.diagnosticRequest.longtermTreatmentTpl +
      vmodel.diagnosticRequest.emergencyTreatmentTpl +
      vmodel.diagnosticRequest.otherTreatmentTpl +
      remark.content
    )
  }
  return remark.content || ''
}

// 生成复诊病历文字描述
export function genReviewEmrTextContent(
  fragmentReviewVModel,
  fragmentReviewVModelOriginal,
  birthDate
) {
  let age = moment().diff(moment(birthDate), 'year')
  let temp = [
    {
      name: '复诊',
      text: [serialize.reviewChiefComplaint(fragmentReviewVModel)],
      imgUrls: [],
      isNameAdded: false,
    },
    {
      name: '体格检查',
      text: [serialize.bodyCheck(fragmentReviewVModel)],
      imgUrls: [],
      isNameAdded: false,
    },
    {
      name: '辅助检查',
      text: [serialize.assExam(fragmentReviewVModel)],
      imgUrls: $utils
        .pureCopy(fragmentReviewVModel.assExam.lungThumbnail || [])
        .concat(
          $utils.pureCopy(fragmentReviewVModel.assExam.allergenImgurl || [])
        ),
      isNameAdded: false,
    },
    {
      name: '诊断',
      text: [serialize.diagnostic(fragmentReviewVModel, age)],
      imgUrls: [],
      isNameAdded: false,
    },
    {
      name: '治疗方案',
      text: [serialize.diagnosticRequest(fragmentReviewVModel)],
      imgUrls: [],
      isNameAdded: false,
    },
    {
      name: '检查结果',
      text: [serialize.checkResult(fragmentReviewVModel)],
      imgUrls: [],
      isNameAdded: false,
    },
    {
      name: '附件',
      text: [''],
      imgUrls: $utils.pureCopy(fragmentReviewVModel.attachments),
      isNameAdded: false,
    },
  ]

  temp = temp.filter((item) => item.text[0] || item.imgUrls.length)
  return temp
}

// @兼容:个人史->既往史+个人史
// 设置以前病历里面的缺省值
export function clearDefaultValue(data, original, key) {
  if ($utils.isBoolean(original[key]) || $utils.isNull(original[key])) {
    data[key] = null
  }
  if ($utils.isString(original[key]) || $utils.isNumber(original[key])) {
    data[key] = ''
  }
  if ($utils.isArray(original[key])) {
    data[key] = []
  }
}

// 转化长期
export function parseEmergencyTreatment(contents) {
  let ret = ''
  contents.forEach((item) => {
    ret += `${item.commonName} ${
      item.drugSpec ? '(' + item.drugSpec + ')' : ''
    } ${item.quantityPerDosageHigh || ''}${item.drugUnit} ${
      item.frequencyLatinHigh
    } ${item.remarkHigh};\r\n`
  })

  return ret
}

// 转化急性药物
export function parseTreatment(contents) {
  let ret = ''
  contents.forEach((item) => {
    let light = item.quantityPerDosageLow
      ? `绿区：${item.quantityPerDosageLow}${item.drugUnit} 
      ${item.frequencyLatinLow} ${item.remarkLow};`
      : ''
    let medium = item.quantityPerDosageMedium
      ? `黄区：${item.quantityPerDosageMedium}${item.drugUnit} 
      ${item.frequencyLatinMedium} ${item.remarkMedium};`
      : ''
    let high = item.quantityPerDosageHigh
      ? `红区：${item.quantityPerDosageHigh}${item.drugUnit} 
      ${item.frequencyLatinHigh} ${item.remarkHigh};`
      : ''
    ret += `${item.commonName} ${
      item.drugSpec ? '(' + item.drugSpec + ')' : ''
    } ${light} ${medium} ${high}\r\n`
  })

  return ret
}
